<script setup lang="ts">
import {ref} from 'vue'
import http from '../utils/http.ts'
import {ElMessage} from 'element-plus'

const emit = defineEmits(['saved'])


const appServerEmptyObject = {
  serverName: '',
  hostIp: ''
}

const appServer = ref<AppServerNew | AppServer>({...appServerEmptyObject})

const dialogTitle = ref('')
const dialogVisible = ref(false)

async function init(id = 0) {
  dialogVisible.value = true
  if (id) {
    dialogTitle.value = '修改服务'
    appServer.value = await http<AppServer>({
      url: `/appServer/${id}`,
    })
  } else {
    dialogTitle.value = '新增服务'
    appServer.value = {...appServerEmptyObject}
  }
}

defineExpose({
  init,
})

async function save() {
  if ((appServer.value as AppServer).id) {
    await http({
      url: '/appServer', method: 'PUT', data: appServer.value,
    })
  } else {
    await http({
      url: '/appServer', method: 'POST', data: appServer.value,
    })
  }
  ElMessage({type: 'success', message: '保存成功'})
  dialogVisible.value = false
  emit('saved')
}
</script>

<template>
  <el-dialog v-model="dialogVisible"
             :title="dialogTitle"
             :close-on-click-modal="true"
             width="500" center
  >
    <el-form
        label-position="right"
        label-width="auto"
        :model="appServer"
        style="max-width: 600px"
    >
      <el-form-item label="服务名称">
        <el-input v-model="appServer.serverName"/>
      </el-form-item>
      <el-form-item label="主机ip">
        <el-input v-model="appServer.hostIp"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="save">Save</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="stylus">
</style>